// 定义data数据
let data = {
    collection: [],
    shopcartlist: []
}
// 接收到修改之前旧的state和action生成新的state 返回新的state
function reducer(state = data, action) {
    // 深拷贝
    // 第一种方式 json.parse(json.stringify(obj)) 深层拷贝：就是如果对象里面还有对象都可以拷贝
    // 第二种方式 object.assign 和{...} 浅层深拷贝：就是只能拷贝到对象的属性，里面的子对象只能拷贝到引用地址
    //收藏相关action处理
    let newState = JSON.parse(JSON.stringify(state))
    if (action.type === "COLLECT") {
        newState.collection.push(action.params)
    } else if (action.type === "UNCOLLECT") {
        let index = newState.collection.findIndex((item, index) => {
            return item.id === action.params.id
        })
        if (index !== -1) {
            newState.collection.splice(index, 1)
        }
    } else if (action.type === "COLLECTLIST") {
        newState.collection = action.params

        //    购物车相关action
    } else if (action.type === "CARTADD") {
        let flag = newState.shopcartlist.find((item, index) => {
            return item.id === action.params.id
        })
        if (flag) {
            flag.count++
        } else {
            action.params = { ...action.params };
            action.params.count = 1
            newState.shopcartlist.push(action.params)
        }
    } else if (action.type === "CARTSUB") {
        let flag = newState.shopcartlist.find((item, index) => {
            return item.id === action.params.id
        })
        if (flag) {
            flag.count--
        }
    } else if (action.type === "CARTLIST") {
        newState.shopcartlist = action.params
    } else if (action.type === "CARTLISTCLEAR") {
        newState.shopcartlist = []
    } else {
        return state
    }
    return newState
}
export default reducer